<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理系统 - 用户管理</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <style>
        body {
            padding-top: 56px;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .sidebar {
            min-height: calc(100vh - 56px);
            position: fixed;
            top: 56px;
            left: 0;
            width: 200px;
            z-index: 100;
            padding: 20px 0;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
            background-color: #343a40;
        }
        .sidebar .nav-link {
            color: #ddd;
            padding: 0.5rem 1rem;
        }
        .sidebar .nav-link:hover {
            color: #fff;
            background-color: rgba(255, 255, 255, 0.1);
        }
        .sidebar .nav-link.active {
            color: #fff;
            background-color: rgba(255, 255, 255, 0.2);
        }
        .sidebar .nav-link i {
            margin-right: 8px;
        }
        .main-content {
            margin-left: 200px;
            padding: 20px;
            flex: 1;
        }
        .user-avatar {
            width: 40px;
            height: 40px;
            object-fit: cover;
            border-radius: 50%;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
        <a class="navbar-brand" href="${pageContext.request.contextPath}/admin">
            <i class="fas fa-dumbbell"></i> 体育商城后台
        </a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item">
                    <a class="nav-link" href="${pageContext.request.contextPath}/" target="_blank">
                        <i class="fas fa-external-link-alt"></i> 访问前台
                    </a>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown">
                        <i class="fas fa-user-circle"></i> ${adminUser}
                    </a>
                    <div class="dropdown-menu dropdown-menu-right">
                        <a class="dropdown-item" href="${pageContext.request.contextPath}/admin/logout">
                            <i class="fas fa-sign-out-alt"></i> 退出登录
                        </a>
                    </div>
                </li>
            </ul>
        </div>
    </nav>

    <!-- 侧边栏 -->
    <jsp:include page="sidebar.jsp" />

    <!-- 主要内容 -->
    <div class="main-content">
        <div class="container-fluid">
            <!-- 标题行 -->
            <div class="row mb-4">
                <div class="col-md-6">
                    <h2 class="mb-1">用户管理</h2>
                    <p class="text-muted">管理所有注册用户</p>
                </div>
                <div class="col-md-6 text-right">
                    <button class="btn btn-primary" id="addUserBtn">
                        <i class="fas fa-plus"></i> 添加用户
                    </button>
                </div>
            </div>
            
            <!-- 搜索过滤器 -->
            <div class="row mb-4">
                <div class="col-md-12">
                    <div class="card shadow-sm">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="searchUsername">用户名</label>
                                        <input type="text" class="form-control" id="searchUsername" placeholder="输入用户名">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="searchStatus">状态</label>
                                        <select class="form-control" id="searchStatus">
                                            <option value="">全部状态</option>
                                            <option value="1">正常</option>
                                            <option value="0">禁用</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-4 d-flex align-items-end">
                                    <button class="btn btn-primary btn-block" id="searchBtn">
                                        <i class="fas fa-search"></i> 搜索
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 用户列表 -->
            <div class="row">
                <div class="col-md-12">
                    <div class="card shadow-sm">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>头像</th>
                                            <th>用户名</th>
                                            <th>邮箱</th>
                                            <th>手机号</th>
                                            <th>注册时间</th>
                                            <th>状态</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="userTableBody">
                                        <tr>
                                            <td colspan="8" class="text-center">正在加载数据...</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- 分页 -->
                            <nav aria-label="Page navigation" class="mt-4">
                                <ul class="pagination justify-content-center" id="pagination">
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 用户表单模态框 -->
    <div class="modal fade" id="userModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="userModalTitle">添加用户</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="userForm">
                        <input type="hidden" id="userId">
                        
                        <div class="form-group">
                            <label for="userName">用户名 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="userName" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="userPassword">密码 <span class="text-danger" id="passwordRequired">*</span></label>
                            <input type="password" class="form-control" id="userPassword">
                            <small class="form-text text-muted" id="passwordHelpText">请输入6-20位字符的密码</small>
                        </div>
                        
                        <div class="form-group">
                            <label for="userEmail">邮箱</label>
                            <input type="email" class="form-control" id="userEmail">
                        </div>
                        
                        <div class="form-group">
                            <label for="userPhone">手机号</label>
                            <input type="text" class="form-control" id="userPhone">
                        </div>
                        
                        <div class="form-group">
                            <label for="userStatus">状态</label>
                            <select class="form-control" id="userStatus">
                                <option value="1">正常</option>
                                <option value="0">禁用</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveUserBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- jQuery 和 Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            let currentPage = 1;
            let pageSize = 10;
            let totalPages = 0;
            
            // 加载用户列表
            function loadUsers(page = 1) {
                currentPage = page;
                
                let url = "${pageContext.request.contextPath}/admin/users/list?pageNum=" + page + "&pageSize=" + pageSize;
                
                // 添加过滤条件
                const username = $('#searchUsername').val();
                const status = $('#searchStatus').val();
                
                if (username) url += "&username=" + encodeURIComponent(username);
                if (status !== "") url += "&status=" + status;
                
                $.get(url, function(res) {
                    if (res.code == 200 || res.success == true) {
                        renderUsers(res.data.records || []);
                        renderPagination(res.data.current, res.data.pages);
                        totalPages = res.data.pages;
                    } else {
                        alert("加载用户失败: " + res.message);
                    }
                });
            }
            
            // 渲染用户列表
            function renderUsers(users) {
                const $tbody = $('#userTableBody');
                $tbody.empty();
                
                if (users.length === 0) {
                    $tbody.html('<tr><td colspan="8" class="text-center">没有找到用户数据</td></tr>');
                    return;
                }
                
                users.forEach(function(user) {
                    const statusBadge = user.status == 1 
                        ? '<span class="badge badge-success">正常</span>' 
                        : '<span class="badge badge-danger">禁用</span>';
                    
                    const defaultAvatar = "${pageContext.request.contextPath}/static/images/default-avatar.jpg";
                    const avatarSrc = user.avatar || defaultAvatar;
                    const createTime = user.createTime ? new Date(user.createTime).toLocaleString() : '';
                    const email = user.email || '-';
                    const phone = user.phone || '-';
                    
                    let statusBtn = '';
                    if (user.status == 1) {
                        statusBtn = '<button class="btn btn-sm btn-outline-danger status-btn" data-id="' + user.id + '" data-status="0">' +
                                    '<i class="fas fa-ban"></i> 禁用</button>';
                    } else {
                        statusBtn = '<button class="btn btn-sm btn-outline-success status-btn" data-id="' + user.id + '" data-status="1">' +
                                    '<i class="fas fa-check"></i> 启用</button>';
                    }
                    
                    let tr = '<tr>' +
                        '<td>' + user.id + '</td>' +
                        '<td><img src="' + avatarSrc + '" class="user-avatar" alt="' + user.username + '"></td>' +
                        '<td>' + user.username + '</td>' +
                        '<td>' + email + '</td>' +
                        '<td>' + phone + '</td>' +
                        '<td>' + createTime + '</td>' +
                        '<td>' + statusBadge + '</td>' +
                        '<td>' + 
                            statusBtn + 
                            ' <button class="btn btn-sm btn-outline-primary edit-user-btn ml-1" data-id="' + user.id + '">' +
                            '<i class="fas fa-edit"></i> 编辑</button>' +
                        '</td>' +
                        '</tr>';
                    $tbody.append(tr);
                });
                
                // 绑定状态按钮事件
                $('.status-btn').click(function() {
                    const userId = $(this).data('id');
                    const status = $(this).data('status');
                    updateUserStatus(userId, status);
                });
                
                // 绑定编辑按钮事件
                $('.edit-user-btn').click(function() {
                    const userId = $(this).data('id');
                    editUser(userId);
                });
            }
            
            // 渲染分页
            function renderPagination(current, total) {
                const $pagination = $('#pagination');
                $pagination.empty();
                
                if (total <= 1) return;
                
                let startPage = Math.max(1, current - 2);
                let endPage = Math.min(total, current + 2);
                
                // 上一页
                let prevDisabled = current == 1 ? 'disabled' : '';
                $pagination.append(
                    '<li class="page-item ' + prevDisabled + '">' +
                    '<a class="page-link" href="javascript:;" data-page="' + (current - 1) + '">上一页</a>' +
                    '</li>'
                );
                
                // 页码
                for (let i = startPage; i <= endPage; i++) {
                    let active = i == current ? 'active' : '';
                    $pagination.append(
                        '<li class="page-item ' + active + '">' +
                        '<a class="page-link" href="javascript:;" data-page="' + i + '">' + i + '</a>' +
                        '</li>'
                    );
                }
                
                // 下一页
                let nextDisabled = current == total ? 'disabled' : '';
                $pagination.append(
                    '<li class="page-item ' + nextDisabled + '">' +
                    '<a class="page-link" href="javascript:;" data-page="' + (current + 1) + '">下一页</a>' +
                    '</li>'
                );
                
                // 绑定分页点击事件
                $('.page-link').click(function() {
                    if (!$(this).parent().hasClass('disabled')) {
                        const page = $(this).data('page');
                        loadUsers(page);
                    }
                });
            }
            
            // 更新用户状态
            function updateUserStatus(userId, status) {
                const statusText = status == 1 ? '启用' : '禁用';
                const confirmMsg = `确定要${statusText}该用户吗？`;
                
                if (confirm(confirmMsg)) {
                    $.ajax({
                        url: "${pageContext.request.contextPath}/admin/users/status/" + userId + "/" + status,
                        type: "POST",
                        success: function(res) {
                            if (res.code == 200 || res.success == true) {
                                alert(`${statusText}成功`);
                                loadUsers(currentPage);
                            } else {
                                alert(`${statusText}失败: ` + res.message);
                            }
                        },
                        error: function() {
                            alert(`${statusText}失败，服务器错误`);
                        }
                    });
                }
            }
            
            // 搜索按钮点击
            $('#searchBtn').click(function() {
                loadUsers(1);
            });
            
            // 添加用户按钮点击
            $('#addUserBtn').click(function() {
                showUserModal(false);
            });
            
            // 保存用户按钮点击
            $('#saveUserBtn').click(function() {
                saveUser();
            });
            
            // 显示用户模态框
            function showUserModal(isEdit) {
                if (!isEdit) {
                    // 添加模式
                    $('#userModalTitle').text('添加用户');
                    $('#userForm').trigger('reset');
                    $('#userId').val('');
                    $('#passwordRequired').show();
                    $('#userPassword').attr('required', true);
                    $('#passwordHelpText').show();
                } else {
                    // 编辑模式
                    $('#userModalTitle').text('编辑用户');
                    $('#passwordRequired').hide();
                    $('#userPassword').attr('required', false);
                    $('#passwordHelpText').text('不修改密码请留空');
                }
                
                $('#userModal').modal('show');
            }
            
            // 编辑用户
            function editUser(userId) {
                $.get("${pageContext.request.contextPath}/admin/users/detail/" + userId, function(res) {
                    if (res.code == 200 || res.success == true) {
                        const user = res.data;
                        
                        // 填充表单
                        $('#userId').val(user.id);
                        $('#userName').val(user.username);
                        $('#userEmail').val(user.email || '');
                        $('#userPhone').val(user.phone || '');
                        $('#userStatus').val(user.status);
                        
                        // 显示编辑模态框
                        showUserModal(true);
                    } else {
                        alert("获取用户信息失败: " + res.message);
                    }
                }).fail(function() {
                    alert("获取用户信息失败，服务器错误");
                });
            }
            
            // 保存用户
            function saveUser() {
                // 表单验证
                if (!$('#userName').val()) {
                    alert('请输入用户名');
                    return;
                }
                
                const isEdit = $('#userId').val() !== '';
                
                if (!isEdit && !$('#userPassword').val()) {
                    alert('请输入密码');
                    return;
                }
                
                // 构建提交的数据
                const userData = {
                    username: $('#userName').val(),
                    email: $('#userEmail').val(),
                    phone: $('#userPhone').val(),
                    status: parseInt($('#userStatus').val()),
                    role: 0  // 默认为普通用户
                };
                
                // 编辑模式要添加ID
                if (isEdit) {
                    userData.id = parseInt($('#userId').val());
                }
                
                // 仅在添加模式或者密码非空时添加密码
                if (!isEdit || $('#userPassword').val()) {
                    userData.password = $('#userPassword').val();
                }
                
                $.ajax({
                    url: "${pageContext.request.contextPath}/admin/users/" + (isEdit ? "update" : "add"),
                    type: "POST",
                    contentType: "application/json",
                    data: JSON.stringify(userData),
                    success: function(res) {
                        if (res.code == 200 || res.success == true) {
                            alert(isEdit ? "更新用户成功" : "添加用户成功");
                            $('#userModal').modal('hide');
                            loadUsers(isEdit ? currentPage : 1);
                        } else {
                            alert((isEdit ? "更新用户失败: " : "添加用户失败: ") + res.message);
                        }
                    },
                    error: function() {
                        alert(isEdit ? "更新用户失败，服务器错误" : "添加用户失败，服务器错误");
                    }
                });
            }
            
            // 初始加载
            loadUsers();
        });
    </script>
</body>
</html> 